<?php
/**
 * 数据库工厂类
 * 
 * @author 祝文博<kevinroot@163.com>
 * @create 2013-09-02 23:31:40
 * @note:
 * 		该类用于创建数据库操作实体，包括创建如下类
 * 		Zend_Db_Table
 * 		Zend_Db_Select
 * 		Zend_Db_Adapter
 */
class Db_Factory
{
	protected static $_instance		= null;
	
	/**
	 * 数据库配置
	 * @var Zend_Config
	 */
	protected $_configs			= array();
	
	/**
	 * 数据库对象Zend_Db_Adapter_Abstract
	 * @var Zend_Db_Adapter_Abstract
	 */
	protected $_db				= null;
	
	/**
	 * 设置数据库名
	 * @var String
	 */
	protected $_dbName			= '';
	
	/**
	 * 数据表列表
	 * @var Array
	 */
	protected $_tables			= array();
	
	protected function __construct()
	{
		$db	= Zend_Db::factory(
			Zend_Registry::get('db')->db->adapter, 
			Zend_Registry::get('db')->db->param
		);
		$this->_db = $db;
	}
	
	/**
	 * 设置数据库配置
	 * @param array|Zend_Config $configs
	 */
	public function setConfigs($configs)
	{
		if (is_array($configs)) {
			$this->_configs = new Zend_Config($configs);
		} else if ($configs instanceof Zend_Config) {
			$this->_configs = $configs;
		}
	}
	
	/**
	 * 获取实例
	 * @return Db_Factory
	 */
	public static function getInstance()
	{
		if (null === self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	/**
	 * 析构单例实体数据（由于有些请求很耗时间，这段时间可能会让数据库超时）
	 */
	public static function destructInstance()
	{
		self::$_instance	= null;
	}
	
	/**
	 * 创建数据表对象
	 * @param String $table 数据表名称
	 * @param String $dbName 数据库名称
	 * @return Zend_Db_Table
	 */
	public function createTable($table, $dbName = '')
	{
		if ($dbName) {
			$this->setDbName($dbName);
		}
		$dbName = $this->getDbName();
		
		if (!isset($this->_tables[$dbName][$table])) {
			$config = array(
				'db'	=> $this->_db,
				'name'	=> $table
			);
			$this->_tables[$dbName][$table] = new Zend_Db_Table($config);
		}
		return $this->_tables[$dbName][$table];
	}
	
	/**
	 * 创建数据库适配器类Zend_Db_Adapter_Abstract
	 * @return Zend_Db_Adapter_Abstract
	 */
	public function getDb()
	{
		return $this->_db;
	}
	
	/**
	 * 创建Zend_Db_Select对象
	 * @return Zend_Db_Select
	 */
	public function createSelect()
	{
		return $this->_db->select();
	}
	
	/**
	 * 获取当前数据库名称
	 * @return String
	 */
	public function getDbName()
	{
		return $this->_dbName;
	}
	
	/**
	 * 设置当前数据库名称
	 * @param String $dbName
	 */
	public function setDbName($dbName)
	{
		$this->_dbName = (string) $dbName;
		return $this;
	}
}